<?php
namespace jy_levelfee;
defined('BY_JYA') or exit('error');
/*
	分销佣金
	
*/
class commission extends \plugin{
	/*
		生成佣金
	*/
	function create($order){
		$this->order=$order;
		$this->order['onegoodsnum']=count($this->order['goods']);
		$member=$this->get('member',array('mid'=>$order['mid']));
		if($this->setting['self_commission']==1){
			$level=3;
			$agent_id=$order['mid'];
		}else{
			$level=2;
			$agent_id=$member['agent_id'];
			//自购升级
			if($member['is_agent']){
				$this->update('member',array('myorder_price +='=>$order['price']),array('mid'=>$order['mid']));
				$this->model('member')->update_agent_level($order['mid']);
			}
		}
		$this->commission_order=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$this->order['mid'],
			'ordersn'=>$this->order['ordersn'],
			'order_price'=>$this->order['price'],
			'plugin_name'=>$this->order['plugin_name']?:'',
			'commission_money'=>0,
			'createtime'=>TIMESTAMP,
		);
		//佣金计算方式，是否扣除运费
		if($this->setting['commissiontype']==1){
			$this->commission_order['commission_price']=$this->order['price'];
		}else{
			$this->commission_order['commission_price']=$this->order['price']-$this->order['dispatchprice'];
		}
		$parameter=array(
			'params'=>array('uniacid'=>$_SESSION['uniacid']),
			'orderby'=>'level desc',
			'limit'=>'1',
		);		
		$levels=$this->get_list('level',$parameter);
		$this->commission_order['maxlevel_id']=$maxlevel=$levels[0]['id'];
		//当分销层级大于0时，逐次寻找上级推荐人并计算佣金
		for($i=0;$i<$level;$i++){
			if(!$agent_id){
				break;
			}
			$istwo=$i+1==$level?:false;
			$nowmember=$this->get('member',array('mid'=>$agent_id));
			if(!$istwo){
				$onelevel_id=$nowmember['level_id'];
			}
			$agent_id=$nowmember['agent_id'];
			//各种佣金独立
			if($this->setting['is_onefee']==1){
				if($nowmember['level_id'] && $nowmember['level_id']==$member['level_id']){//平级分红
					if(!$istwo){
						$oneispingji=1;
						$this->create_redcommission($nowmember);
					}elseif($oneispingji !=1){
						$this->create_redcommission($nowmember);
					}
				}elseif($istwo && $nowmember['level_id'] && $nowmember['level_id']==$onelevel_id){//间推模式下，直推平级
					$this->create_redcommission($nowmember);
				}elseif($maxlevel && $maxlevel==$nowmember['level_id']){
					if($member['level_id']==0){
						$this->create_commission($nowmember,$istwo);
					}else{
						$this->create_maxcommission($nowmember);
					}
				}else{
					$this->create_commission($nowmember,$istwo);
				}
			}else{
				$this->create_commission($nowmember,$istwo);
				//平级分红
				if($nowmember['level_id'] && $nowmember['level_id']==$member['level_id']){
					$this->create_redcommission($nowmember);
				}
				//最大总代分红
				if($maxlevel && $maxlevel==$nowmember['level_id']){
					$this->create_maxcommission($nowmember);
				}
			}
			//如果他的上级是我
			$ta_agent_id=$this->getcolumn('member',array('mid'=>$agent_id),'agent_id');
			if($ta_agent_id==$nowmember['agent_id']){
				break;
			}
		}
		//生成分销订单
		$indata=$this->commission_order;
		unset($indata['maxlevel_id']);
		$this->insert('order',$indata);
		return true;
	}
	/*
		给指定会员的计算佣金
		统一佣金比例佣金计算比较简单
		但是商品独立佣金设置该当如何计算呢？
		首先遍历订单的所有商品
			逐个商品检查是否存在独立佣金规则，如果存在，则将订单中该商品的金额单独拿出来计算佣金，订单金额剩余部分在统一计算佣金
	*/
	function create_commission($member,$istwo){
		$agent_id=$member['mid'];
		if($member && $member['is_agent'] && $member['stop']==0){
			$money=0;
			$order_price=$this->commission_order['commission_price'];
			$remark=array(
				'level_id'=>$level_id,
				'istwo'=>$istwo,
				'order_price'=>$order_price,
				'goods_commission'=>array(),
			);	
			//先检查是否存在商品独立佣金规则，如果存在则对订单相应商品部分金额单独计算佣金
			$total_lastcostprice=0;
			//非按笔计算
			foreach($this->order['goods'] as $goods){
					if($this->order['onegoodsnum']>1 && !$goods['fee_desc']){
						model('jy_weishop/order')->setfee_desc($goods['orderid']);
					}
					$fees=$this->get_fee($goods,$setting,$member,$istwo);
					$buynum=$fees['buynum'];
					$order_price=$order_price-$fees['total_price'];
					if($this->order['onegoodsnum']==1 && $fees['commission_money']>0){
						$order_price=0;
					}
					$total_costprice=$goods['total']*$fees['goodscostprice'];
					$total_lastcostprice +=$total_costprice;
					$money+=$fees['commission_money'];
					$remark['goods_commission'][]=array('buynum'=>$buynum,'ordergoodsid'=>$goods['id'],'goods_id'=>$goods['goodsid'],'total_price'=>$fees['total_price'],'total'=>$goods['total'],'commission_per'=>$fees['commission_per'],'commission_money'=>$fees['commission_money']);	
			}
			if($order_price>0){
				$fees=$this->get_lastorderfee($order_price,$total_lastcostprice,$setting,$member,$istwo,$buynum);
				$buynum=$fees['buynum']?:$buynum;
				$money+=$fees['commission_money'];
				$remark['order_commission']=array('buynum'=>$buynum,'order_price'=>$order_price,'commission_per'=>$fees['commission_per'],'commission_money'=>$fees['commission_money']);
			}
			$remark['commission_money']=$money;
			if($money>0){
				$this->commission_order['commission_money']+=$money;
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$member['mid'],
					'level'=>$istwo?2:1,
					'ordersn'=>$this->order['ordersn'],
					'money'=>$money,
					'remark'=>ijson_encode($remark),
					'createtime'=>TIMESTAMP,
					'status'=>0,
				);
				$this->insert('commission',$new_commission);
				model('jy_weishop/notice')->notice_fenxiao_feeadd($agent_id,$new_commission['money']);
			}
			//此处判断分销商是否满足升级条件，如果满足则升级分销商等级
			$member_update=array(
				'order_price'=>$member['order_price']+$this->commission_order['order_price'],
				'order_num'=>$member['order_num']+1,
			);
			if($commission_level==1){
				$member_update['order_price_next']=$member['order_price_next']+$this->commission_order['order_price'];
				$member_update['order_num_next']=$member['order_num_next']+1;
			}
			$this->update('member',$member_update,array('mid'=>$member['mid']));
			$this->model('member')->update_agent_level($member['mid']);
		}
		return $member['agent_id'];
	}
	//平级分红
	function create_redcommission($member){
		$agent_id=$member['mid'];
		$level_id=$member['level_id'];
		if($member && $member['is_agent'] && $member['stop']==0){
			$money=0;
			$order_price=$this->commission_order['commission_price'];
			$remark=array(
				'level_id'=>$level_id,
				'istwo'=>$istwo,
				'order_price'=>$order_price,
				'goods_commission'=>array(),
			);	
			//先检查是否存在商品独立佣金规则，如果存在则对订单相应商品部分金额单独计算佣金
			$total_lastcostprice=0;
			//非按笔计算
			foreach($this->order['goods'] as $goods){
					if($this->order['onegoodsnum']>1 && !$goods['fee_desc']){
						model('jy_weishop/order')->setfee_desc($goods['orderid']);
					}
					$fees=$this->get_goodslevelfee($goods,$member);
					$order_price=$order_price-$fees['total_price'];
					if($this->order['onegoodsnum']==1 && $fees['commission_money']>0){
						$order_price=0;
					}
					$money+=$fees['commission_money'];
					$remark['goods_commission'][]=array('ordergoodsid'=>$goods['id'],'goods_id'=>$goods['goodsid'],'total_price'=>$fees['total_price'],'total'=>$goods['total'],'commission_per'=>$fees['commission_per'],'commission_money'=>$fees['commission_money']);	
			}
			if($order_price>0){
				$fees=$this->get_orderlevelfee($order_price,$member);
				$money+=$fees['commission_money'];
				$remark['order_commission']=array('order_price'=>$order_price,'commission_per'=>$fees['commission_per'],'commission_money'=>$fees['commission_money']);
			}
			$remark['commission_money']=$money;
			if($money>0){
				$this->commission_order['commission_money']+=$money;
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$member['mid'],
					'level'=>1,
					'ordersn'=>$this->order['ordersn'],
					'money'=>$money,
					'remark'=>ijson_encode($remark),
					'createtime'=>TIMESTAMP,
					'status'=>0,
					'type'=>1,
				);
				$this->insert('commission',$new_commission);
				model('jy_weishop/notice')->notice_fenxiao_feeadd($agent_id,$new_commission['money']);
			}
		}
		return $member['agent_id'];
	}
	//最大等级分红
	function create_maxcommission($member){
		$agent_id=$member['mid'];
		$level_id=$member['level_id'];
		if($member && $member['is_agent'] && $member['stop']==0){
			$money=0;
			$order_price=$this->commission_order['commission_price'];
			$remark=array(
				'level_id'=>$level_id,
				'istwo'=>$istwo,
				'order_price'=>$order_price,
				'goods_commission'=>array(),
			);	
			//先检查是否存在商品独立佣金规则，如果存在则对订单相应商品部分金额单独计算佣金
			$total_lastcostprice=0;
			//非按笔计算
			foreach($this->order['goods'] as $goods){
					if($this->order['onegoodsnum']>1 && !$goods['fee_desc']){
						model('jy_weishop/order')->setfee_desc($goods['orderid']);
					}
					$fees=$this->get_goodsmaxlevelfee($goods,$member);
					$order_price=$order_price-$fees['total_price'];
					if($this->order['onegoodsnum']==1 && $fees['commission_money']>0){
						$order_price=0;
					}
					$money+=$fees['commission_money'];
					$remark['goods_commission'][]=array('ordergoodsid'=>$goods['id'],'goods_id'=>$goods['goodsid'],'total_price'=>$fees['total_price'],'total'=>$goods['total'],'commission_per'=>$fees['commission_per'],'commission_money'=>$fees['commission_money']);	
			}
			if($order_price>0){
				$fees=$this->get_ordermaxlevelfee($order_price);
				$money+=$fees['commission_money'];
				$remark['order_commission']=array('order_price'=>$order_price,'commission_per'=>$fees['commission_per'],'commission_money'=>$fees['commission_money']);
			}
			$remark['commission_money']=$money;
			if($money>0){
				$this->commission_order['commission_money']+=$money;
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$member['mid'],
					'level'=>1,
					'ordersn'=>$this->order['ordersn'],
					'money'=>$money,
					'remark'=>ijson_encode($remark),
					'createtime'=>TIMESTAMP,
					'status'=>0,
					'type'=>2,
				);
				$this->insert('commission',$new_commission);
				model('jy_weishop/notice')->notice_fenxiao_feeadd($agent_id,$new_commission['money']);
			}
		}
		return $member['agent_id'];
	}
	/*
		获取本单的佣金明细,$istwo表示间推
	*/
	protected function get_fee($goods,$setting=array(),$member=array(),$istwo=false){
		if(is_array($goods)){
			$goods_id=$goods['goodsid'];
			$isorder=true;
		}else{
			$goods_id=$goods;
		}
		$setting=$setting?:$this->setting;
		$fees=array();
		$ignore=$this->get('goods',array('goods_id'=>$goods_id),array('id','ignore'));
		if($isorder && $goods['optionid']){
			$goodsinfo=pdo_get('jy_weishop_goods_option',array('goodsid'=>$goods_id,'id'=>$goods['optionid']),array('costprice','price'));
			$goodscostprice=$goodsinfo['costprice'];
		}else{
			$goodsinfo=pdo_get('jy_weishop_goods',array('id'=>$goods_id),array('costprice','price'));
			$goodscostprice=$goodsinfo['costprice'];
		}
		$fees['goodscostprice']=$goodscostprice;
		$goodsprice=$this->order['onegoodsnum']>1?$goodsinfo['price']:$this->order['price'];
		$fees['commission_money']=0;
		//复购次数：
		if($this->setting['fu_buynum']==1){
			$buynum=$this->get_rentous($_SESSION['uid'],$goods_id,$istwo);
		}elseif($this->setting['fu_buynum']==2){
			$buynum=pdo_count('jy_weishop_order_goods',array('ispay'=>1,'mid'=>$_SESSION['uid'],'goodsid'=>$goods_id),'id');
			if($buynum<=1){
				$buynum=$this->get_rentous($_SESSION['uid'],$goods_id,$istwo);
			}
		}elseif($this->setting['fu_buynum']==3){
			if($istwo){
				$buynum=$this->get_rentous($_SESSION['uid'],$goods_id,$istwo);
			}else{
				$buynum=pdo_count('jy_weishop_order_goods',array('ispay'=>1,'mid'=>$_SESSION['uid'],'goodsid'=>$goods_id),'id');
			}
		}else{
			$buynum=pdo_count('jy_weishop_order_goods',array('ispay'=>1,'mid'=>$_SESSION['uid'],'goodsid'=>$goods_id),'id');
		}
		$fees['buynum']=$buynum;
		if($ignore['ignore']==1){
			$fees['total_price']=$isorder?$goodsprice:$goodsinfo['price'];
			$fees['goodscostprice']=0;
			return $fees;
		}elseif(!$ignore['id']){			
			$fees['total_price']=0;
			return $fees;
		}
		$fees['total_price']=$isorder?$goods['total_price']:0;
		$fee_num=intval($setting['fee_num'])?:4;
		$goodsprice=$this->order['onegoodsnum']>1?$goodsinfo['price']:$this->order['price'];
		if($ignore['id'] && $ignore['ignore']!=1){
			$goods_commission=$this->get('goods',array('goods_id'=>$goods_id));
			$goods_commission['commissions']=$goods_commission['commissions']?json_decode($goods_commission['commissions'],true):array();
			foreach($goods_commission['commissions'] as $gc){
							//默认等级
							if($gc['level_id']==0){
								if(!$istwo){
									if($buynum<=1){
										$demogoods_commission_per=$gc['commission1_0'];	
									}elseif($buynum<$fee_num){
										$demogoods_commission_per=$gc['commission1_1'];	
									}else{
										$demogoods_commission_per=$gc['commission1_2'];	
									}
									if($this->setting['fu_buynum']==3){
										//不存在复购，复购没佣金
										if(!$gc['commission1_1']){
										//if($buynum>1){
											$demobuynum=$this->get_rentous($_SESSION['uid'],$goods_id);
											if($demobuynum>=$fee_num && $buynum==1){
												$demogoods_commission_per=$gc['commission1_2'];	
											}elseif($buynum==1){
												$demogoods_commission_per=$gc['commission1_0'];
											}else{
												$demogoods_commission_per=0;
											}
										//}
										}elseif($buynum>1){
											$demogoods_commission_per=$gc['commission1_1'];	
										}
									}
								}else{
									if($buynum<$fee_num){
										$demogoods_commission_per=$gc['commission2_0'];	
									}else{
										$demogoods_commission_per=$gc['commission2_1'];	
									}
								}
							}
							if($gc['level_id']!=$member['level_id']){
								continue;
							}else{
								if(!$istwo){
									if($buynum<=1){
										$goods_commission_per=$gc['commission1_0'];	
									}elseif($buynum<$fee_num){
										$goods_commission_per=$gc['commission1_1'];	
									}else{
										$goods_commission_per=$gc['commission1_2'];	
									}
									if($this->setting['fu_buynum']==3){
										if(!$gc['commission1_1']){
										//if($buynum>1){
											$newbuynum=$this->get_rentous($_SESSION['uid'],$goods_id);
											if($newbuynum>=$fee_num && $buynum==1){
												$goods_commission_per=$gc['commission1_2'];	
											}elseif($buynum==1){
												$goods_commission_per=$gc['commission1_0'];
											}else{
												$goods_commission_per=0;
											}
										//}
										}elseif($buynum>1){
											$goods_commission_per=$gc['commission1_1'];	
										}
									}
								}else{
									if($buynum<$fee_num){
										$goods_commission_per=$gc['commission2_0'];	
									}else{
										$goods_commission_per=$gc['commission2_1'];	
									}
								}
								break;
							}
			}
			$goods_commission_per=$goods_commission_per?:$demogoods_commission_per;	
			if(substr($goods_commission_per,-1)=='%'){
							//利润计算
							if($setting['commissionfeetype']==2){
								$goodsprice -=$goodscostprice;
							}
							$goods_commission_money=($goodsprice*substr($goods_commission_per,0,-1))/100;
			}else{
							$goods_commission_money=$goods_commission_per;
			}
			$fees['commission_per']=$goods_commission_money;
			$fees['commission_money']=$goods_commission_money?price($goods_commission_money,true):0;
		}else{
			$fees['commission_money']=0;
		}
		//重置次数
		$fees['buynum']=$newbuynum?:$demobuynum;
		$fees['buynum']=$fees['buynum']?:$buynum;
		return $fees;
	}
	/*
		获取等级默认的佣金明细,$istwo表示间推
	*/
	protected function get_lastorderfee($order_price,$total_lastcostprice,$setting=array(),$member=array(),$istwo=false,$buynum=1,$goods_id=''){
			if(!$member['level_id']){
						//获取默认等级佣金比例
						$level_commissions=$this->plugin_setting('default_level');
						$level_id=0;
			}else{
						$level=$this->get('level',array('id'=>$member['level_id'],'uniacid'=>$_SESSION['uniacid']));
						$level_commissions=json_decode($level['commissions'],true);
						$level_id=$level['id'];
			}
			$fee_num=intval($this->setting['fee_num'])?:4;
			if(!$istwo){
					if($buynum<=1){
						$commission_per=$level_commissions['commission1_0'];	
					}elseif($buynum<$fee_num){
						$commission_per=$level_commissions['commission1_1'];	
					}else{
						$commission_per=$level_commissions['commission1_2'];	
					}
					if($this->setting['fu_buynum']==3){
						if(!$level_commissions['commission1_1']){
								//if($buynum>1){
								$goods_id=$goods_id?:$this->order['goods'][0]['goodsid'];
								$newbuynum=$this->get_rentous($_SESSION['uid'],$goods_id);
								if($newbuynum>=$fee_num && $buynum==1){
									$commission_per=$level_commissions['commission1_2'];	
								}elseif($buynum==1){
									$commission_per=$level_commissions['commission1_0'];
								}else{
									$commission_per=0;
								}
								//}
						}elseif($buynum>1){
								$commission_per=$level_commissions['commission1_1'];	
						}
					}
			}else{
					if($buynum<$fee_num){
						$commission_per=$level_commissions['commission2_0'];	
					}else{
						$commission_per=$level_commissions['commission2_1'];	
					}
			}
			//利润计算
			if($this->setting['commissionfeetype']==2){
					$order_price -=$total_lastcostprice;
			}
			if(substr($goods_commission_per,-1)=='%'){
					$order_commission_money=($order_price*substr($commission_per,0,-1))/100;
			}else{
					$order_commission_money=$commission_per;
			}
			$fees['buynum']=$newbuynum?:$buynum;
			$fees['commission_per']=$commission_per;
			$fees['commission_money']=$order_commission_money>0?price($order_commission_money,true):0;
			return $fees;
	}
	/*
		获取订单平级分红
	*/
	protected function get_orderlevelfee($order_price,$member=array()){
			$fees=array('commission_money'=>0);
			if(!$member['level_id']){
					return $fees;
			}else{
				$level=$this->get('level',array('id'=>$member['level_id'],'uniacid'=>$_SESSION['uniacid']));
				$level_commissions=json_decode($level['commissions'],true);
				$level_id=$level['id'];
			}
			$commission_per=$level_commissions['levelfee'];
			if(substr($goods_commission_per,-1)=='%'){
					$order_commission_money=($order_price*substr($commission_per,0,-1))/100;
			}else{
					$order_commission_money=$commission_per;
			}
			$fees['commission_per']=$commission_per;
			$fees['commission_money']=$order_commission_money>0?price($order_commission_money,true):0;
			return $fees;
	}
	/*
		获取商品平级分红
	*/
	protected function get_goodslevelfee($goods,$member=array()){
		if(is_array($goods)){
			$goods_id=$goods['goodsid'];
			$isorder=true;
		}else{
			$goods_id=$goods;
		}
		$fees=array();
		$ignore=$this->get('goods',array('goods_id'=>$goods_id),array('id','ignore'));
		if($isorder && $goods['optionid']){
			$goodsinfo=pdo_get('jy_weishop_goods_option',array('goodsid'=>$goods_id,'id'=>$goods['optionid']),array('costprice','price'));
		}else{
			$goodsinfo=pdo_get('jy_weishop_goods',array('id'=>$goods_id),array('costprice','price'));
		}
		$goodsprice=$this->order['onegoodsnum']>1?$goodsinfo['price']:$this->order['price'];
		$fees['commission_money']=0;
		if($ignore['ignore']==1){
			$fees['total_price']=$isorder?$goodsprice:$goodsinfo['price'];
			return $fees;
		}elseif(!$ignore['id']){
			$fees['total_price']=0;
			return $fees;
		}
		$fees['total_price']=$isorder?$goods['total_price']:0;
		$goodsprice=$this->order['onegoodsnum']>1?$goodsinfo['price']:$this->order['price'];
		if($ignore['id'] && $ignore['ignore']!=1){
			$goods_commission=$this->get('goods',array('goods_id'=>$goods_id));
			$goods_commission['commissions']=$goods_commission['commissions']?json_decode($goods_commission['commissions'],true):array();
			foreach($goods_commission['commissions'] as $gc){
							//默认等级
							if($gc['level_id']==0){
								$demogoods_commission_per=$gc['levelfee'];
							}
							if($gc['level_id']!=$member['level_id']){
								continue;
							}else{
								$goods_commission_per=$gc['levelfee'];
								break;
							}
			}
			$goods_commission_per=$goods_commission_per?:$demogoods_commission_per;	
			if(substr($goods_commission_per,-1)=='%'){
					$goods_commission_money=($goodsprice*substr($goods_commission_per,0,-1))/100;
			}else{
					$goods_commission_money=$goods_commission_per;
			}
			$fees['commission_per']=$goods_commission_money;
			$fees['commission_money']=$goods_commission_money?price($goods_commission_money,true):0;
		}else{
			$fees['commission_money']=0;
		}
		return $fees;
	}
	/*
		获取订单最大分红
	*/
	protected function get_ordermaxlevelfee($order_price,$setting=array()){
			$fees=array('commission_money'=>0);
			$setting=$setting?:$this->setting;
			if(!$setting['open_maxlevelfee'] || !$setting['maxlevelfee']){
				return $fees;
			}
			$commission_per=$setting['maxlevelfee'];
			if(substr($goods_commission_per,-1)=='%'){
					$order_commission_money=($order_price*substr($commission_per,0,-1))/100;
			}else{
					$order_commission_money=$commission_per;
			}
			$fees['commission_per']=$commission_per;
			$fees['commission_money']=$order_commission_money>0?price($order_commission_money,true):0;
			return $fees;
	}
	/*
		获取商品最大等级分红
	*/
	protected function get_goodsmaxlevelfee($goods,$member=array(),$setting=array()){
		$setting=$setting?:$this->setting;
		if(!$setting['open_maxlevelfee']){
			return $fees;
		}
		if(is_array($goods)){
			$goods_id=$goods['goodsid'];
			$isorder=true;
		}else{
			$goods_id=$goods;
		}
		$fees=array();
		$ignore=$this->get('goods',array('goods_id'=>$goods_id),array('id','ignore'));
		if($isorder && $goods['optionid']){
			$goodsinfo=pdo_get('jy_weishop_goods_option',array('goodsid'=>$goods_id,'id'=>$goods['optionid']),array('costprice','price'));
		}else{
			$goodsinfo=pdo_get('jy_weishop_goods',array('id'=>$goods_id),array('costprice','price'));
		}
		$goodsprice=$this->order['onegoodsnum']>1?$goodsinfo['price']:$this->order['price'];
		$fees['commission_money']=0;
		if($ignore['ignore']==1){
			$fees['total_price']=$isorder?$goodsprice:$goodsinfo['price'];
			return $fees;
		}elseif(!$ignore['id']){
			$fees['total_price']=0;
			return $fees;
		}
		$fees['total_price']=$isorder?$goods['total_price']:0;
		$goodsprice=$this->order['onegoodsnum']>1?$goodsinfo['price']:$this->order['price'];
		if($ignore['id'] && $ignore['ignore']!=1){
			$goods_commission=$this->get('goods',array('goods_id'=>$goods_id));
			$goods_commission['commissions']=$goods_commission['commissions']?json_decode($goods_commission['commissions'],true):array();
			foreach($goods_commission['commissions'] as $gc){
					if($gc['level_id']==$member['level_id']){
						$goods_commission_per=$gc['maxlevelfee'];
						break;
					}
			}
			$goods_commission_per=$goods_commission_per;	
			if(substr($goods_commission_per,-1)=='%'){
					$goods_commission_money=($goodsprice*substr($goods_commission_per,0,-1))/100;
			}else{
					$goods_commission_money=$goods_commission_per;
			}
			$fees['commission_per']=$goods_commission_money;
			$fees['commission_money']=$goods_commission_money?price($goods_commission_money,true):0;
		}else{
			$fees['commission_money']=0;
		}
		return $fees;
	}
	/*
		订单完成时，把佣金状态由初始的订单待完成升级为待结算
	*/
	public function order_complete($order){
		$this->update('commission',array('status'=>1,'complete_time'=>TIMESTAMP),array('status'=>0,'ordersn'=>$order['ordersn']));
	}
	/*
		创建结算单
	*/
	public function create_balance($mid,$post=array()){
		if(!$mid){
			exi('请先选择要结算的会员！','error');
		}
		if($post['pay_type']=='alipay'){
			if(!$post['realname']){
				exi('请先填写真实姓名！','error');
			}
			if(!$post['alipay']){
				exi('请先填写支付宝帐号！','error');
			}
			if(!$post['alipay1']){
				exi('请确认帐号','error');
			}
			if($post['alipay1']!=$post['alipay']){
				exi('确认帐号与支付宝帐号不匹配！','error');
			}
		}
		if($post['pay_type']=='union'){
			if(!$post['realname']){
				exi('请输入姓名','error');
			}
			if(!$post['bankname']){
				exi('请输入所属银行','error');
			}
			if(!$post['bankcard']){
				exi('请银行卡号','error');
			}
			if(!$post['bankcard1']){
				exi('请确认卡号','error');
			}
			if($post['bankcard']!=$post['bankcard1']){
				exi('确认卡号与银行卡号不匹配！','error');
			}
		}
		//获取可结算佣金
		$params=array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid,'status'=>1);
		if($this->setting['balance_day']){
			//结算天数
			$time=TIMESTAMP-intval($this->setting['balance_day'])*86400;
			$params['complete_time <']=$time;
		}
		$commissions=$this->getall('commission',$params);
		if(!$commissions){
			exi('没有可结算的佣金！','error');
		}
		$commission_num=count($commissions);
		$money=0;
		foreach($commissions as $commission){
			$money+=$commission['money'];
		}
		//结算最低佣金检测
		if($money<$this->setting['balance_money']){
			exi('可结算佣金太少，无法结算！','error');
		}
		$new_balance=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$mid,
			'balancesn'=>get_ordersn($this->tablename('commission'),'balancesn','AC'),
			'commission_num'=>$commission_num,
			'money'=>$money,
			'pay_type'=>$post['pay_type'],
			'realname'=>$post['realname'],
			'alipay'=>$post['alipay'],
			'bankname'=>$post['bankname'],
			'bankcard'=>$post['bankcard'],
			'createtime'=>TIMESTAMP,
			'status'=>0,
		);
		//结算手续费
		if($this->setting['balance_per']){
			$new_balance['balance_pay']=intval($new_balance['money']*$this->setting['balance_per'])/100;
		}else{
			$new_balance['balance_pay']=0;
		}
		$new_balance['final_money']=$new_balance['money']-$new_balance['balance_pay'];
		$this->insert('balance',$new_balance);
		$balance_id=pdo_insertid();
		foreach($commissions as $commission){
			$update=array(
				'status'=>2,
				'balancesn'=>$new_balance['balancesn'],
			);
			$this->update('commission',$update,array('id'=>$commission['id']));
		}
		return $balance_id;
	}
	/*
		审核结算单
	*/
	public function check_balance($balance_id,$status,$remark=''){
		$update=array(
			'status'=>$status,
			'check_time'=>TIMESTAMP,
			'remark'=>$remark,
		);
		$this->update('balance',$update,array('id'=>$balance_id));
	}
	/*
		打款结算单
	*/
	public function pay_balance($balance_id,$pay_type='',$wxgid='',$pay_trade_no=''){
		$balance=$this->get('balance',array('id'=>$balance_id,'uniacid'=>$_SESSION['uniacid']));
		if(!$balance || $balance['status']!=1){
			exi('结算单不存在或者不符合打款条件，打款失败！','error');
		}
		$pay_types=array_keys($this->pay_types);
		if(!$pay_type || !in_array($pay_type,$pay_types)){
			//exi('未设置打款方式或者打款方式不合法，打款失败！','error');
		}
		$func_name='pay_balance_by_'.$pay_type;
		$trade_no=$this->$func_name($balance['mid'],$balance['final_money'],$balance['balancesn'],$wxgid);
		$update=array(
			'status'=>3,
			'pay_trade_no'=>$trade_no=='pay_trade_no'?$pay_trade_no:$trade_no,
			'pay_time'=>TIMESTAMP,
		);
		if($pay_type){
			$update['pay_type']=$pay_type;
		}
		$this->update('balance',$update,array('id'=>$balance['id']));
		return true;
	}
	/*
		打款到余额
	*/
	protected function pay_balance_by_credit($mid,$money,$balancesn){
		return cfc('core')->member_credit($mid,'credit2',$money,true,$this->plugin_name,$remark='分销佣金打款');
	}
	/*
		打款到微信零钱
	*/
	protected function pay_balance_by_wechat($mid,$money,$balancesn,$wxgid=''){
		if($wxgid){
			$wxapp=pdo_get('core_account_wxapp',array('id'=>$wxgid,'uniacid'=>$_SESSION['uniacid']),array('appid','mchid','paykey'));
		}
		$params=array(
			'appid'=>$wxapp['appid']?:'',
			'mch_id'=>$wxapp['mchid']?:'',
			'openid'=>$mid,
			'mch_billno'=>$balancesn,
			'money'=>$money,
			'wxgid'=>$wxgid,
			'remark'=>'代理商佣金发放',
		);
		$res=cfc('wechat_pay')->mch_pay($params);
		return $res['payment_no'];
	}
	/*
		打款到支付宝
	*/
	protected function pay_balance_by_alipay($mid,$money,$balancesn){
		return 'pay_trade_no';
		exi('暂不支持打款到支付宝！','error');
	}
	/*
		打款到银行账户
	*/
	protected function pay_balance_by_union($mid,$money,$balancesn){
		return 'pay_trade_no';
		exi('暂不支持打款到银行账户！','error');
	}

	public function commission_remark($remark){
		if(!$remark){
			return '';
		}
		$remark=json_decode($remark,true);
		$goods_str='';
		if($remark['goods_commission']){
			foreach($remark['goods_commission'] as $goods){
				$goods['title']=pdo_getcolumn('jy_weishop_goods',array('id'=>$goods['goods_id']),'title');
				$buynum=$goods['buynum'];
				$goods_str.="商品ID【{$goods['goods_id']}】，商品名称【{$goods['title']}】，商品数量【{$goods['total']}】，商品总价【{$goods['total_price']}】，第【{$goods['buynum']}】次购买，佣金规则【{$goods['commission_per']}】，分销佣金【{$goods['commission_money']}】\n";
			}
		}else{
			$goods_str='未启用';
		}
		$remark['level_title']=pdo_getcolumn('jy_levelfee_level',array('uniacid'=>$_SESSION['uniacid'],'level'=>$remark['commission_level']),'title');
		$remark['level_title']=$remark['level_title']?:'默认等级';
		$remark_str=<<<TPL
分销商等级ID【{$remark['level_id']}】，等级名称【{$remark['level_title']}】，佣金等级【{$remark['commission_level']}】，订单总价【{$remark['order_price']}】，第【{$buynum}】次购买，
商品独立佣金：
{$goods_str}
订单佣金：
除去设置独立佣金的商品外订单金额【{$remark['order_commission']['order_price']}】，佣金规则【{$remark['order_commission']['commission_per']}%】，分销佣金【{$remark['order_commission']['commission_money']}】
佣金总计：【{$remark['commission_money']}】
TPL;
		return $remark_str;
	}
	/*
		获取单独商品佣金
	*/
	protected function get_goodsfee($goodsid,$orderid,$ordergoodsid=''){
		$ordersn=pdo_getcolumn('jy_weishop_order',array('id'=>$orderid,'uniacid'=>$_SESSION['uniacid']),'ordersn');
		$commissionremark=$this->pdo_getcolumn('commission',array('ordersn'=>$ordersn,'uniacid'=>$_SESSION['uniacid']),'remark');
		//print_r($ordersn.'~~'.$commissionremark);exit;
		$commissionremark=json_decode($commissionremark,true);
		
		$goodsfee=0;
		if($commissionremark['goods_commission']){
			foreach($commissionremark['goods_commission'] as $gv){
				if($ordergoodsid){
					if($ordergoodsid==$gv['ordergoodsid']){
						$goodsfee +=$gv['commission_money'];
					}
				}else{
					if($goodsid==$gv['goods_id']){
						$goodsfee +=$gv['commission_money'];
					}
				}
			}
		}
		if($commissionremark['order_commission'] && $goodsfee==0){
			$allorderfee=pdo_getsum('jy_weishop_order_goods',array('orderid'=>$orderid,'goodsid'=>$goodsid),'total_price');
			//exi($allorderfee.'~'.$commissionremark['order_commission']['order_price'].'~'.$commissionremark['order_commission']['commission_money'],'error');
			$goodsfee=($allorderfee/$commissionremark['order_commission']['order_price'])*$commissionremark['order_commission']['commission_money'];
		}
		return $goodsfee;
	}
	/*
		获取单独商品佣金
	*/
	public function get_rentous($mid,$goods_id,$istwo=false){
			$mid=$mid?:$_SESSION['uid'];
			$member=$this->get('member',array('mid'=>$mid));
			//获取我的上级，下面的直推
			$zhituis=$this->getall('member',array('uniacid'=>$_SESSION['uniacid'],'agent_id'=>$member['agent_id']),array('mid'),'mid');
			if(!$zhituis){
					$zhituis=0;
			}else{
					$zhituis=array_keys($zhituis);
					$buyorders=pdo_getall('jy_weishop_order_goods',array('ispay'=>1,'mid'=>$zhituis,'goodsid'=>$goods_id),array('id','goodsid','mid'));
					$onegoods=array();
					foreach($buyorders as &$bv){
						$onegoods[$bv['mid']]=$bv;
					}
					$zhituibuys=count($onegoods);
			}
			if(!$istwo){
				return $zhituibuys;
			}else{
				//获取我的上级的上级
				$twoagent_id=$this->getcolumn('member',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$member['agent_id']),'agent_id');
				//获取我的上级的上级,的直推
				$zhituis=$this->getall('member',array('uniacid'=>$_SESSION['uniacid'],'agent_id'=>$twoagent_id),array('mid'),'mid');
				if(!$zhituis){
						$zhituis=0;
				}else{
						$zhituis=array_keys($zhituis);
						//获取我的上级的上级,的间推
						$twotuis=$this->getall('member',array('agent_id'=>$zhituis),array('mid'),'mid');
						if(count($twotuis)){
							$twotuis=array_keys($twotuis);
							$buyorders=pdo_getall('jy_weishop_order_goods',array('ispay'=>1,'mid'=>$twotuis,'goodsid'=>$goods_id),array('id','goodsid','mid'));
							$onegoods=array();
							foreach($buyorders as &$bv2){
								$onegoods[$bv2['mid']]=$bv2;
							}
							$jiantuibuys=count($onegoods);
						}
				}
				return $jiantuibuys;
			}
			
	}
}